<!--组织树-->
<template>
  <div id="organizationTree" class="flex-main">
    <el-cascader
      ref="cascader"
      v-model="selectedOrgIds"
      :options="treeDatas"
      :props="{ leaf: 'leaf',checkStrictly: true,value:'id',multiple :multiple }"
      @change="handleNodeClick" />
  </div>
</template>
<script>
export default {
  props: {
    value: {
      type: Array,
      required: false,
      default() {
        return []
      }
    },
    multiple: { type: Boolean, default: false }, // 多选单选
    isDept: { type: Boolean, default: true }
  },
  data() {
    return {
      defaultTreeProps: {
        children: 'children',
        label: 'organizationName'
      },
      selectedOrgIds: [],
      treeDatas: [],
      listQuery: {
        type: this.isDept ? null : 1
      },
      fullPathName: [],
      fullPathId: []
    }
  },
  watch: {
    selectedOrgIds: function(val) {
      this.$emit('input', val)
    },
    value: function(val) {
      if (!val) {
        this.$nextTick(() => {
          this.$refs.cascader.panel.checkedValue = []
          this.$refs.cascader.panel.activePath = []
          this.$refs.cascader.panel.syncActivePath()
          // this.$refs.cascader.clearCheckedNodes()
        })
      }
      setTimeout(() => {
        this.selectedOrgIds = val
      }, 200)
    }
  },
  mounted() {},
  created() {
    this.loadOrganizationTree()
  },
  methods: {
    async loadOrganizationTree() {
      this.treeDatas.length = 0
      this.treeLoading = true
      this.listQuery.pid = 0
      const response = await this.$store.dispatch('loadOrganizationTree', this.listQuery)
      this.treeDatas = this.getTreeData(response)
      this.treeLoading = false
    },
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined
        } else {
          this.getTreeData(data[i].children)
        }
      }
      return data
    },
    handleNodeClick() {
      var nodes = this.$refs.cascader.getCheckedNodes()
      var lastLevelDatas = []
      nodes.forEach(item => {
        lastLevelDatas.push({
          id: item.data.id,
          pid: item.data.ext1,
          name: item.data.label,
          type: item.data.ext
        })
      })
      if (this.multiple) {
        this.$emit('change', lastLevelDatas)
      } else {
        if (lastLevelDatas.length > 0) {
          this.$emit('change', lastLevelDatas[0])
        } else {
          this.$emit('change', {})
        }
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" >

</style>
